<template>
  <div class="login">
    <el-row class="login_row">
      <el-col :xs="0" :sm="0" :md="12" :lg="16" :xl="16" class="login_left">
        <!-- <img src="@/assets/images/login-background.jpg" alt=""> -->
        <!-- <el-image :src="back" fit="cover" /> -->
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" class="login_right">
        <!-- Dark -->
        <Dark></Dark>
        <!-- Dark End -->
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
          <h3 class="title">秘密基地</h3>
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="手机号登录" name="0">
              <el-form-item prop="username">
                <el-input
                  v-model="loginForm.username"
                  type="text"
                  size="large"
                  auto-complete="off"
                  placeholder="手机号"
                >
                  <template #prepend>
                    <el-icon size="18"><Iphone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-input
                  v-model="loginForm.code"
                  type="number"
                  size="large"
                  auto-complete="off"
                  placeholder="验证码"
                  @keyup.enter="handleLogin"
                >
                  <template #prepend>
                    <el-icon size="18"><Lock /></el-icon>
                  </template>
                  <template #append>
                    <div class="loginCode">获取验证码</div>
                  </template>
                </el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="密码登录" name="1">
              <el-form-item prop="username">
                <el-input
                  v-model="loginForm.username"
                  type="text"
                  size="large"
                  auto-complete="off"
                  placeholder="账号"
                >
                  <template #prepend>
                    <el-icon size="18"><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  size="large"
                  auto-complete="off"
                  placeholder="密码"
                  @keyup.enter="handleLogin"
                >
                  <template #prepend>
                    <el-icon size="18"><Lock /></el-icon
                  ></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled">
                <el-input
                  class="login-code-input"
                  v-model="loginForm.code"
                  size="large"
                  auto-complete="off"
                  placeholder="验证码"
                  @keyup.enter="handleLogin"
                >
                  <template #prepend>
                    <el-icon size="18"><Iphone /></el-icon
                  ></template>
                </el-input>
                <div class="login-code">
                  <img fit="fill" :src="codeUrl" @click="getCode" class="login-code-img" />
                </div>
              </el-form-item>
              <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px"
                >记住密码</el-checkbox
              >
            </el-tab-pane>
          </el-tabs>

          <el-form-item style="width: 100%">
            <el-button
              :loading="loading"
              size="large"
              type="primary"
              style="width: 100%"
              class="loginBtn"
              @click.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2024-2025 lijunxuan.top</span>
    </div>
  </div>
</template>

<script setup>
import useUserStore from "@/stores/modules/user";
import Cookies from "js-cookie";
import Dark from "@/components/Dark";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { getCodeImg } from "@/api/login";
const { proxy } = getCurrentInstance();

// pinia
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

// tabs
const activeName = ref("1");

//挂载
onMounted(() => {
  getUserPwd();
});

// 监听路由变化
watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

const handleClick = (tab, event) => {
};
// tabs end

const getUserPwd = () => {
  let rememberMe = Cookies.get("rememberMe");
  if (rememberMe) {
    loginForm.value.username = Cookies.get("username");
    loginForm.value.password = decrypt(Cookies.get("password"));
    loginForm.value.rememberMe = Boolean(rememberMe);
  }
};

const setUserPwd = () => {
  // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
  if (loginForm.value.rememberMe) {
    Cookies.set("username", loginForm.value.username, { expires: 30 });
    Cookies.set("password", encrypt(loginForm.value.password), {
      expires: 30,
    });
    Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
  } else {
    // 否则移除
    Cookies.remove("username");
    Cookies.remove("password");
    Cookies.remove("rememberMe");
  }
};

const handleLogin = () => {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 调用action的登录方法


      let loginData = { ...loginForm.value };
      loginData.password = encrypt(loginForm.value.password);
      // loginData.password = loginForm.value.password;
      userStore
        .login(loginData)
        .then(() => {
          const query = route.query;

          setUserPwd();
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({ path: redirect.value || "/", query: otherQueryParams });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
};

const getCode = () => {
  // codeUrl.value = import.meta.env.VITE_APP_BASE_API + "/user/captcha";
  getCodeImg().then((res) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = res.data.img;
    }
  });
};
getCode();
</script>
<style lang="scss">
.login {
  .el-tabs__header {
    margin-bottom: 20px;
  }
  .el-tabs__content{height: 351px;}
  .el-tabs__nav-wrap:after {
    opacity: 0 !important;
  }
  .el-tabs__item {
    font-size: var(--el-font-size-large);
  }
}
</style>
<style lang="scss" scoped>
.login {
  height: 100vh;
  width: 100vw;
  &_row {
    height: 100%;
  }
  &_left {
    background-image: url("@/assets/images/login-background.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    opacity: var(--dark-opacity);
  }
  &_right {
    @include flexBox(row, center, null);
    .dark-switch{
      @include posBox(fixed,null,20px,20px);
    }
  }
}
.title {
  font-size: 36px;
  font-weight: bold;
  margin: 0px 0 80px;
}

.login-form {
  @include flexBox(column, center, null);
  border-radius: 6px;
  max-width: 490px;
  min-width: 300px;
  width: calc(100% - 100px);
  // padding: 25px 25px 5px 25px;
  // .el-form-item {
  //   margin-bottom: 30px;
  // }
  .el-input {
    height: 50px;
    margin: 15px 5px;
    box-shadow: var(--dark-boxshadow);
    input {
      height: 50px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
  .loginBtn {
    background: #5777fe;
    box-shadow: 0 0 14px 0px #5777fe;
    height: 57px;
    font-size: 18px;
    font-weight: bold !important;
    margin-top: 30px;
    border-radius: 8px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code-input {
  width: calc(100% - 182px);
}
.login-code {
  width: 160px;
  height: 50px;
  float: right;
  margin-left: 12px;
  border-radius: 4px;
  overflow: hidden;
  img {
    cursor: pointer;
    vertical-align: middle;
    height: 50px;
    width: 100%;
  }
}
.el-login-footer {
  height: 50px;
  line-height: 50px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #888;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.loginCode {
  cursor: pointer;
  font-weight: bold;
  color: var(--el-color-primary);
}
</style>
